﻿using System;
using System.Collections.Generic;
using System.Text;

using System.IO;

namespace EdgeStatz.ESSystems.Logs
{
    public class LogWriter
    {
        private static TextWriter fileErrors = null;
        private static TextWriter fileActivity = null;
        private static TextWriter fileSql = null;
        private static string fileNameErrors = "EdgeStatz.Errors.log";
        private static string fileNameActivity = "EdgeStatz.Activity.log";
        private static string fileNameSql = "EdgeStatz.Sql.log";
        
        public static void SetFilePath(string path)
        {
            if (!path.Trim().EndsWith("\\")) { path = path.Trim() + "\\Logs\\"; } else { path = path.Trim() + "Logs\\"; }
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            if(fileErrors == null)
                fileErrors = new StreamWriter(path + fileNameErrors, true);
            if (fileActivity == null)
                fileActivity = new StreamWriter(path + fileNameActivity, true);
            if (fileSql == null)
                fileSql = new StreamWriter(path + fileNameSql, true);
        }

        public static void WriteToLog(string message, LogType type) 
        {
            if (fileErrors == null || fileActivity == null || fileSql == null)
                throw new NullReferenceException("Log File(s) are null. The path must be set before writing to the file.");
            switch (type)
            {
                case LogType.Error:
                    fileErrors.WriteLine(DateTime.Now + ":\tError:\t" + message);
                    fileErrors.WriteLine();
                    break;
                case LogType.Warning:
                    fileErrors.WriteLine(DateTime.Now + ":\tWarning:\t" + message);
                    fileErrors.WriteLine();
                    break;
                case LogType.Activity:
                    fileActivity.WriteLine(DateTime.Now + ":\tActivity:\t" + message);
                    fileActivity.WriteLine();
                    break;
                case LogType.Transaction:
                    fileActivity.WriteLine(DateTime.Now + ":\tTransaction:\t" + message);
                    fileActivity.WriteLine();
                    break;
                case LogType.Sql:
                    fileSql.WriteLine(DateTime.Now + ":\tSql:\t" + message);
                    fileSql.WriteLine();
                    break;
            }
        }

        public static void Close()
        {
            if (fileErrors != null)
                fileErrors.Close();
            if (fileActivity != null)
                fileActivity.Close();
            if (fileSql != null)
                fileSql.Close();
            fileErrors = null;
            fileActivity = null;
            fileSql = null;
        }
    }

    public enum LogType { Error, Warning, Transaction, Activity, Sql }
}
